package com.tms.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tms.basic.mapper.VehicleMapper;
import com.tms.basic.pojo.domain.Vehicle;
import com.tms.basic.pojo.req.VehicleQueryReq;
import com.tms.basic.pojo.vo.VehicleVO;
import com.tms.basic.service.VehicleService;
import com.tms.common.core.common.Constant;
import com.tms.common.core.domain.R;
import com.tms.common.core.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 车辆信息服务实现类
 *
 * @author TMS
 * @since 2024-01-01
 */
@Service
@RequiredArgsConstructor
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {

    private final VehicleMapper vehicleMapper;

    @Override
    public R<IPage<VehicleVO>> getVehiclePage(VehicleQueryReq req) {
        try {
            Page<VehicleVO> page = new Page<>(req.getCurrent(), req.getSize());
            IPage<VehicleVO> result = vehicleMapper.selectVehiclePage(page, req);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询车辆信息失败：" + e.getMessage());
        }
    }

    @Override
    public R<List<VehicleVO>> getVehicleList(VehicleQueryReq req) {
        try {
            List<VehicleVO> result = vehicleMapper.selectVehicleList(req);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询车辆列表失败：" + e.getMessage());
        }
    }

    @Override
    public R<VehicleVO> getVehicleById(Long id) {
        if (id == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆ID"));
        }
        
        try {
            VehicleVO result = vehicleMapper.selectVehicleById(id);
            if (result == null) {
                return R.failed(String.format(Constant.ErrorMessage.RECORD_NOT_FOUND, id));
            }
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询车辆详情失败：" + e.getMessage());
        }
    }

    @Override
    public R<VehicleVO> getVehicleByLicensePlate(String licensePlate) {
        if (!StringUtils.hasText(licensePlate)) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车牌号"));
        }
        
        try {
            VehicleVO result = vehicleMapper.selectVehicleByLicensePlate(licensePlate);
            if (result == null) {
                return R.failed("未找到车牌号为 " + licensePlate + " 的车辆");
            }
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询车辆信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> addVehicle(Vehicle vehicle) {
        if (vehicle == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆信息"));
        }
        
        try {
            // 检查车牌号是否已存在
            if (isLicensePlateExists(vehicle.getLicensePlate(), null)) {
                return R.failed(String.format(Constant.ErrorMessage.LICENSE_PLATE_EXISTS, vehicle.getLicensePlate()));
            }
            
            boolean result = this.save(vehicle);
            return result ? R.success(true, "车辆添加成功") : R.failed("车辆添加失败");
        } catch (Exception e) {
            throw new BusinessException("车辆添加失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> updateVehicle(Vehicle vehicle) {
        if (vehicle == null || vehicle.getId() == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆信息或车辆ID"));
        }
        
        try {
            // 检查车牌号是否已存在（排除自己）
            if (isLicensePlateExists(vehicle.getLicensePlate(), vehicle.getId())) {
                return R.failed(String.format(Constant.ErrorMessage.LICENSE_PLATE_EXISTS, vehicle.getLicensePlate()));
            }
            
            boolean result = this.updateById(vehicle);
            return result ? R.success(true, "车辆修改成功") : R.failed("车辆修改失败");
        } catch (Exception e) {
            throw new BusinessException("车辆修改失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> deleteVehicle(Long id) {
        if (id == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆ID"));
        }
        
        try {
            boolean result = this.removeById(id);
            return result ? R.success(true, "车辆删除成功") : R.failed("车辆删除失败");
        } catch (Exception e) {
            throw new BusinessException("车辆删除失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> deleteVehicleBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆ID列表"));
        }
        
        try {
            boolean result = this.removeByIds(ids);
            return result ? R.success(true, "批量删除车辆成功") : R.failed("批量删除车辆失败");
        } catch (Exception e) {
            throw new BusinessException("批量删除车辆失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> updateVehicleStatus(Long id, Integer status) {
        if (id == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆ID"));
        }
        if (status == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "车辆状态"));
        }
        
        // 验证状态值的有效性
        if (status < Constant.VehicleStatus.AVAILABLE || status > Constant.VehicleStatus.SCRAPPED) {
            return R.validateFailed(String.format(Constant.ErrorMessage.INVALID_STATUS, status));
        }
        
        try {
            Vehicle vehicle = new Vehicle();
            vehicle.setId(id);
            vehicle.setCurrentStatus(status);
            boolean result = this.updateById(vehicle);
            return result ? R.success(true, "车辆状态更新成功") : R.failed("车辆状态更新失败");
        } catch (Exception e) {
            throw new BusinessException("车辆状态更新失败：" + e.getMessage(), e);
        }
    }

    @Override
    public R<List<VehicleVO>> getExpiringVehicles(Integer days) {
        try {
            if (days == null || days <= 0) {
                days = Constant.DefaultValue.DEFAULT_REMIND_DAYS;
            }
            List<VehicleVO> result = vehicleMapper.selectExpiringVehicles(days);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询即将到期车辆失败：" + e.getMessage());
        }
    }

    @Override
    public R<List<Map<String, Object>>> countVehicleByStatus(Long organizationId) {
        try {
            List<Map<String, Object>> result = vehicleMapper.countVehicleByStatus(organizationId);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("统计车辆状态失败：" + e.getMessage());
        }
    }

    @Override
    public boolean isLicensePlateExists(String licensePlate, Long excludeId) {
        if (!StringUtils.hasText(licensePlate)) {
            return false;
        }
        
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<Vehicle>()
                .eq(Vehicle::getLicensePlate, licensePlate);
        
        if (excludeId != null) {
            queryWrapper.ne(Vehicle::getId, excludeId);
        }
        
        return this.count(queryWrapper) > 0;
    }
} 